{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "GN0Za3IxvXYt"
   },
   "source": [
    "##### Copyright 2020 The OpenFermion Developers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "id": "9a6cAc4RvZxz"
   },
   "outputs": [],
   "source": [
    "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "# https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ejEETb5cvfY-"
   },
   "source": [
    "# Circuits 1: Compiling arbitrary single-particle basis rotations in linear depth"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "vsTKqKQQwFLZ"
   },
   "source": [
    "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://quantumai.google/openfermion/tutorials/circuits_1_basis_change\"><img src=\"https://quantumai.google/site-assets/images/buttons/quantumai_logo_1x.png\" />View on QuantumAI</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/OpenFermion/blob/master/docs/tutorials/circuits_1_basis_change.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/colab_logo_1x.png\" />Run in Google Colab</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://github.com/quantumlib/OpenFermion/blob/master/docs/tutorials/circuits_1_basis_change.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/github_logo_1x.png\" />View source on GitHub</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a href=\"https://storage.googleapis.com/tensorflow_docs/OpenFermion/docs/tutorials/circuits_1_basis_change.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/download_icon_1x.png\" />Download notebook</a>\n",
    "  </td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "247e4c8b8caf"
   },
   "source": [
    "This is the first of several tutorials demonstrating the compilation of quantum circuits. These tutorials build on one another and should be studied in order. In this tutorial we will discuss the compilation of circuits for implementing arbitrary rotations of the single-particle basis of an electronic structure simulation. As an example, we show how one can use these methods to simulate the evolution of an arbitrary non-interacting fermion model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Hquc7XA6vqb8"
   },
   "source": [
    "## Setup\n",
    "\n",
    "Install the OpenFermion package:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "5cbe6b680387"
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    import openfermion\n",
    "except ImportError:\n",
    "    !pip install git+https://github.com/quantumlib/OpenFermion.git@master#egg=openfermion"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "0c5ffa498c6a"
   },
   "source": [
    "## Background\n",
    "\n",
    "### Second quantized fermionic operators\n",
    "\n",
    "In order to represent fermionic systems on a quantum computer one must first discretize space. Usually, one expands the many-body wavefunction in a basis of spin-orbitals $\\varphi_p = \\varphi_p(r)$ which are single-particle basis functions. For reasons of spatial efficiency, all NISQ (and even most error-corrected) algorithms for simulating fermionic systems focus on representing operators in second-quantization. Second-quantized operators are expressed using the fermionic creation and annihilation operators, $a^\\dagger_p$ and $a_p$. The action of $a^\\dagger_p$ is to excite a fermion in spin-orbital $\\varphi_p$ and the action of $a_p$ is to annihilate a fermion from spin-orbital $\\varphi_p$. Specifically, if electron $i$ is represented in a space of spin-orbitals $\\{\\varphi_p(r_i)\\}$ then $a^\\dagger_p$ and $a_p$ are related to Slater determinants through the equivalence,\n",
    "$$\n",
    "\\langle r_0 \\cdots r_{\\eta-1} | a^\\dagger_{0} \\cdots a^\\dagger_{\\eta-1} | \\varnothing\\rangle \\equiv \\sqrt{\\frac{1}{\\eta!}}\n",
    "\\begin{vmatrix}\n",
    "\\varphi_{0}\\left(r_0\\right) & \\varphi_{1}\\left( r_0\\right) & \\cdots & \\varphi_{\\eta-1} \\left( r_0\\right) \\\\\n",
    "\\varphi_{0}\\left(r_1\\right) & \\varphi_{1}\\left( r_1\\right) & \\cdots & \\varphi_{\\eta-1} \\left( r_1\\right) \\\\\n",
    "\\vdots & \\vdots & \\ddots & \\vdots\\\\\n",
    "\\varphi_{0}\\left(r_{\\eta-1}\\right) & \\varphi_{1}\\left(r_{\\eta-1}\\right) & \\cdots & \\varphi_{\\eta-1} \\left(r_{\\eta-1}\\right) \\end{vmatrix}\n",
    "$$\n",
    "where $\\eta$ is the number of electrons in the system, $|\\varnothing \\rangle$ is the Fermi vacuum and $\\varphi_p(r)=\\langle r|\\varphi_p \\rangle$ are the single-particle orbitals that define the basis. By using a basis of Slater determinants, we ensure antisymmetry in the encoded state.\n",
    "\n",
    "### Rotations of the single-particle basis\n",
    "\n",
    "Very often in electronic structure calculations one would like to rotate the single-particle basis. That is, one would like to generate new orbitals that are formed from a linear combination of the old orbitals. Any particle-conserving rotation of the single-particle basis can be expressed as\n",
    "$$\n",
    "\\tilde{\\varphi}_p = \\sum_{q} \\varphi_q u_{pq}\n",
    "\\quad\n",
    "\\tilde{a}^\\dagger_p = \\sum_{q} a^\\dagger_q u_{pq}\n",
    "\\quad\n",
    "\\tilde{a}_p = \\sum_{q} a_q u_{pq}^*\n",
    "$$\n",
    "where $\\tilde{\\varphi}_p$, $\\tilde{a}^\\dagger_p$, and $\\tilde{a}^\\dagger_p$ correspond to spin-orbitals and operators in the rotated basis and $u$ is an $N\\times N$ unitary matrix. From the Thouless theorem, this single-particle rotation\n",
    "is equivalent to applying the $2^N \\times 2^N$ operator\n",
    "$$\n",
    "  U(u) = \\exp\\left(\\sum_{pq} \\left[\\log u \\right]_{pq} \\left(a^\\dagger_p a_q - a^\\dagger_q a_p\\right)\\right) \n",
    "$$\n",
    "where $\\left[\\log u\\right]_{pq}$ is the $(p, q)$ element of the matrix $\\log u$.\n",
    "\n",
    "There are many reasons that one might be interested in performing such basis rotations. For instance, one might be interested in preparing the Hartree-Fock (mean-field) state of a chemical system, by rotating from some initial orbitals (e.g. atomic orbitals or plane waves) into the molecular orbitals of the system. Alternatively, one might be interested in rotating from a basis where certain operators are diagonal (e.g. the kinetic operator is diagonal in the plane wave basis) to a basis where certain other operators are diagonal (e.g. the Coulomb operator is diagonal in the position basis). Thus, it is a very useful thing to be able to apply circuits corresponding to $U(u)$ on a quantum computer in low depth.\n",
    "\n",
    "### Compiling linear depth circuits to rotate the orbital basis\n",
    "\n",
    "OpenFermion prominently features routines for implementing the linear depth / linear connectivity basis transformations described in [Phys. Rev. Lett. 120, 110501](https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.120.110501). While we will not discuss this functionality here, we also support routines for compiling the more general form of these transformations which do not conserve particle-number, known as a Bogoliubov transformation, using routines described in [Phys. Rev. Applied 9, 044036](https://journals.aps.org/prapplied/abstract/10.1103/PhysRevApplied.9.044036). We will not discuss the details of how these methods are implemented here and instead refer readers to those papers. All that one needs in order to compile the circuit $U(u)$ using OpenFermion is the $N \\times N$ matrix $u$, which we refer to in documentation as the \"basis_transformation_matrix\". Note that if one intends to apply this matrix to a computational basis state with only $\\eta$ electrons, then one can reduce the number of gates required by instead supplying the $\\eta \\times N$ rectangular matrix that characterizes the rotation of the occupied orbitals only. OpenFermion will automatically take advantage of this symmetry."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "48803221ec72"
   },
   "source": [
    "## OpenFermion example implementation: exact evolution under tight binding models\n",
    "In this example will show how basis transforms can be used to implement exact evolution under a random Hermitian one-body fermionic operator\n",
    "\\begin{equation}\n",
    "H = \\sum_{pq} T_{pq} a^\\dagger_p a_q.\n",
    "\\end{equation}\n",
    "That is, we will compile a circuit to implement $e^{-i H t}$ for some time $t$. Of course, this is a tractable problem classically but we discuss it here since it is often useful as a subroutine for more complex quantum simulations. To accomplish this evolution, we will use basis transformations. Suppose that $u$ is the basis transformation matrix that diagonalizes $T$. Then, we could implement $e^{-i H t}$ by implementing $U(u)^\\dagger (\\prod_{k} e^{-i \\lambda_k Z_k}) U(u)$ where $\\lambda_k$ are the eigenvalues of $T$. \n",
    "\n",
    "Below, we initialize the T matrix characterizing $H$ and then obtain the eigenvalues $\\lambda_k$ and eigenvectors $u_k$ of $T$. We print out the OpenFermion FermionOperator representation of $T$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "9a9404c74738"
   },
   "outputs": [],
   "source": [
    "import openfermion\n",
    "import numpy\n",
    "\n",
    "# Set the number of qubits in our example.\n",
    "n_qubits = 3\n",
    "simulation_time = 1.\n",
    "random_seed = 8317\n",
    "\n",
    "# Generate the random one-body operator.\n",
    "T = openfermion.random_hermitian_matrix(n_qubits, seed=random_seed)\n",
    "\n",
    "# Diagonalize T and obtain basis transformation matrix (aka \"u\").\n",
    "eigenvalues, eigenvectors = numpy.linalg.eigh(T)\n",
    "basis_transformation_matrix = eigenvectors.transpose()\n",
    "\n",
    "# Print out familiar OpenFermion \"FermionOperator\" form of H.\n",
    "H = openfermion.FermionOperator()\n",
    "for p in range(n_qubits):\n",
    "    for q in range(n_qubits):\n",
    "        term = ((p, 1), (q, 0))\n",
    "        H += openfermion.FermionOperator(term, T[p, q])\n",
    "print(H)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "dd8256e50df5"
   },
   "source": [
    "Now we're ready to make a circuit! First we will use OpenFermion to generate the basis transform $U(u)$ from the basis transformation matrix $u$ by calling the Bogoliubov transform function (named as such because this function can also handle non-particle conserving basis transformations). Then, we'll apply local $Z$ rotations to phase by the eigenvalues, then we'll apply the inverse transformation. That will finish the circuit. We're just going to print out the first rotation to keep things easy-to-read, but feel free to play around with the notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "e086141a3b0a"
   },
   "outputs": [],
   "source": [
    "import openfermion\n",
    "import cirq\n",
    "\n",
    "# Initialize the qubit register.\n",
    "qubits = cirq.LineQubit.range(n_qubits)\n",
    "\n",
    "# Start circuit with the inverse basis rotation, print out this step.\n",
    "inverse_basis_rotation = cirq.inverse(openfermion.bogoliubov_transform(qubits, basis_transformation_matrix))\n",
    "circuit = cirq.Circuit(inverse_basis_rotation)\n",
    "print(circuit)\n",
    "\n",
    "# Add diagonal phase rotations to circuit.\n",
    "for k, eigenvalue in enumerate(eigenvalues):\n",
    "    phase = -eigenvalue * simulation_time\n",
    "    circuit.append(cirq.rz(rads=phase).on(qubits[k]))\n",
    "\n",
    "# Finally, restore basis.\n",
    "basis_rotation = openfermion.bogoliubov_transform(qubits, basis_transformation_matrix)\n",
    "circuit.append(basis_rotation)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "550185877c66"
   },
   "source": [
    "Finally, we can check whether our circuit applied to a random initial state with the exact result. Print out the fidelity with the exact result."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "d3cd633aac46"
   },
   "outputs": [],
   "source": [
    "# Initialize a random initial state.\n",
    "initial_state = openfermion.haar_random_vector(\n",
    "    2 ** n_qubits, random_seed).astype(numpy.complex64)\n",
    "\n",
    "# Numerically compute the correct circuit output.\n",
    "import scipy\n",
    "hamiltonian_sparse = openfermion.get_sparse_operator(H)\n",
    "exact_state = scipy.sparse.linalg.expm_multiply(\n",
    "    -1j * simulation_time * hamiltonian_sparse, initial_state)\n",
    "\n",
    "# Use Cirq simulator to apply circuit.\n",
    "simulator = cirq.Simulator()\n",
    "result = simulator.simulate(circuit, qubit_order=qubits,\n",
    "                            initial_state=initial_state)\n",
    "simulated_state = result.final_state_vector\n",
    "\n",
    "# Print final fidelity.\n",
    "fidelity = abs(numpy.dot(simulated_state, numpy.conjugate(exact_state)))**2\n",
    "print(fidelity)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "e524a8c4bf7b"
   },
   "source": [
    "Thus, we see that the circuit correctly effects the intended evolution. We can now use Cirq's compiler to output the circuit using gates native to near-term devices, and then optimize those circuits. We'll output in QASM 2.0 just to demonstrate that functionality."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "44218407a929"
   },
   "outputs": [],
   "source": [
    "xmon_circuit = cirq.optimize_for_target_gateset(circuit, gateset=cirq.CZTargetGateset())\n",
    "print(xmon_circuit.to_qasm())"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "name": "circuits_1_basis_change.ipynb",
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
